package servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import database.Article;
import database.DatabaseManager;

/**
 * Servlet implementation class NewGiftServlet
 */
public class NewGiftServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewGiftServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    private void newGift(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("utf-8");
    	String title = request.getParameter("title");
    	String content = request.getParameter("content");
    	if(title == null || title.equals("")) {
    		response.sendRedirect(request.getContextPath() + "/newArticleFailed.jsp");
    		return;
    	}
    	if(content == null) {
    		content = "";
    	}

    	int belongTo = ArticleType.GIFT.getBelongTo();

    	HttpSession session = request.getSession();
    	String name = (String) session.getAttribute("name");
    	
    	Date publishTime = new Date();
    	boolean b = DatabaseManager.articlePublish(name, publishTime, belongTo, title);
    	if(!b) {
    		response.sendRedirect(request.getContextPath() + "/newArticleFailed.jsp");
    		return;
    	}
    	
    	Article article = DatabaseManager.articleQueryByCreatInfo(name, publishTime);
    	if(article == null) {
    		b = DatabaseManager.articlePublish(name, publishTime, belongTo, title);
        	if(!b) {
        		response.sendRedirect(request.getContextPath() + "/newArticleFailed.jsp");
        		return;
        	}
    	}
    	if(article == null) {
    		return;
    	}
    	
    	PrintWriter out = new PrintWriter(new File(session.getServletContext().getRealPath("/") + "/file/" + article.getArticleID()));
    	out.print(content);
    	out.close();
    	
    	response.sendRedirect(request.getContextPath() + "/article.jsp?articleID=" + article.getArticleID());
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.newGift(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.newGift(request, response);
	}

}
